<template>
  <div>
    <!-- 搜索与添加按钮 -->
    <el-row :gutter="20">
      <el-col :span="4">
        <el-button type="primary" @click="initComponent">添加广告</el-button>
      </el-col>
    </el-row>

    <!-- 添加用户的对话框 -->
    <el-dialog
        title="添加广告"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogVisible = false">
      <el-form label-width="70px" v-if="addDialogVisible">
        <el-form-item label="标题" prop="title">
          <el-input v-model="bannerForm.title"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="file">
          <input type="file" @change="getFile">
        </el-form-item>
        <el-form-item label="图片" v-if="imageSrc">
          <img :src="imageSrc" class="preview" alt="预览图">
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBanner">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author 太阳当空丶赵
 * @date 2023/1/4-17:06
 * @version 1.0.0
 */

import {uploadBanner} from '@/network/applet'

export default {
  name: "AddBanner",
  data() {
    return {
      addDialogVisible: false,
      bannerForm: {
        title: "",
        file: ""
      },
      imageSrc: ""
    }
  },
  methods: {
    /**
     * 多次添加banner时，组件并没有销毁，所以需要重新初始化数据
     * */
    initComponent() {
      this.addDialogVisible = true
      this.bannerForm.title = ""
      this.bannerForm.file = ""
      this.imageSrc = ""
    },
    async addBanner() {
      // 添加banner
      const {title, file} = this.bannerForm
      const formData = new FormData()
      formData.append("title", title)
      formData.append("file", file)
      const result = await uploadBanner(formData)
      if (result.code !== 200) return this.alertMessage(result.msg, "error")
      this.addDialogVisible = false
      this.alertMessage("添加成功", "success")
      return this.$emit("addBanner")
    },
    getFile(event) {
      // console.log(event)
      this.bannerForm.file = event.target.files[0]
      this.imageSrc = URL.createObjectURL(event.target.files[0])
    }
  }
}
</script>
<style scoped>
.preview {
  width: 100px;
  aspect-ratio: 1;
}
</style>
